<template>
  <ie-page>

    <template #extra>
      <n-space>
        <n-button @click="back">取消</n-button>
        <n-button @click="handleConfirm" type="primary">保存</n-button>
      </n-space>
    </template>

    <ie-form
      :form-inputs="formInputs"
      :form-rules="formRules"
      ref="formRef"
    />
  </ie-page>
</template>

<script setup>
import { ref } from 'vue'
import { useMessage, useNotification } from 'naive-ui'
import { useRouter } from 'vue-router'

import { useApi } from '/@/api'
import { useStore } from '/@/store'

const formRef = ref()
const formInputs = {
  password: {
    title: '旧的密码',
    type: 'password'
  },
  newPassword: {
    title: '新的密码',
    type: 'password'
  },
  confirmPassword: {
    title: '确认密码',
    type: 'password'
  }
}
const formRules = {
  password: { required: true, message: '旧密码不可为空' },
  newPassword: [
    { required: true, message: '新密码不可为空' },
    { min: 6, max: 20, message: '新密码长度应为6-20位' }
  ],
  confirmPassword: { required: true, message: '确认密码不可为空' }
}

const message = useMessage()
const notify = useNotification()
const router = useRouter()

function back() {
  router.back()
}

function handleReset() {
  formRef.value.reset()
}

const store = useStore()

function handleConfirm() {
  const id = store.userInfo?.id

  if (id) {
    formRef.value.submit()
      .then(({
        password,
        newPassword,
        confirmPassword
      }) => {
        if (newPassword !== confirmPassword) return message.error('确认密码不一致，请重新输入')
        if (password === newPassword) return message.error('新旧密码不可相同，请重新输入')

        useApi()
          .post('system-user/password', {
            id,
            old_password: password,
            password: newPassword
          })
          .then(res => {
            if (res.code === 0) {
              notify.success({
                content: '密码修改成功',
                meta: '请重新登录',
                duration: 5e3,
                onAfterEnter() {
                  store.setUser()
                  router.push('/login')
                }
              })
            }
          })
      })
  }
}
</script>